"""
@Time : 2022/7/18 15:34 
@Author : ls
@DES: 
"""
import os
import time
import minio
import numpy
import numpy as np
from pandas import DataFrame
from config import settings
from scipy.spatial import Delaunay
from pyntcloud import PyntCloud
from models.custom_class import InventoryCoalResult


def heap_volume_and_maxheight(coal_heap, cloud_ndarray: numpy.ndarray, minio_path: str, minio_name: str):
    x_list = []
    y_list = []
    for heap_point in coal_heap.coalHeapArea:
        x_list.append(heap_point.x)
        y_list.append(heap_point.y)
        max_x = max(x_list)
        min_x = min(x_list)
        max_y = max(y_list)
        min_y = min(y_list)

    split_ndarray = cloud_ndarray[(cloud_ndarray['x'] < max_x) & (cloud_ndarray['x'] > min_x)
                                  & (cloud_ndarray['y'] < max_y) & (cloud_ndarray['y'] > min_y)]
    # split_ndarray = split_pdarray.values

    # minio_path 为本地的文件名
    # split_ndarray.to_csv(minio_path, index=False, header=False, sep=' ', float_format='%.6f')
    # numpy.savetxt(fname=minio_path, X=split_ndarray, delimiter=' ', fmt='%.2f')
    minio_url = put_cloud(minio_path, minio_name)
    print("*****************************")

    split_ndarray = split_ndarray.values
    if split_ndarray.__len__() < 500:
        return {'maxHeight': 0, 'volume': 0, 'minio_url': minio_url}

    u = split_ndarray[:, 0]  # 这里会报错，如果filename为空，即切割区域没有点云
    v = split_ndarray[:, 1]
    z = split_ndarray[:, 2]
    x = u
    y = v
    maxHeight = max(z) - min(z)

    ply_name = minio_path.replace('.txt', '.ply')
    tri = Delaunay(np.array([u, v]).T)
    f2 = open(ply_name, 'w')
    f2.write('ply\n')
    f2.write('format ascii 1号雷达.0\n')
    f2.write('comment Created by CloudCompare v2.11.3 (Anoia)\n')
    f2.write('comment Created 2021/12/26 19:23\n')
    f2.write('obj_info Generated by CloudCompare!\n')
    f2.write('element vertex ')
    f2.write(str(x.size) + '\n')
    f2.write('property float x\n')
    f2.write('property float y\n')
    f2.write('property float z\n')
    f2.write('element face ')
    f2.write(str(tri.simplices.shape[0]) + '\n')
    f2.write('property list uchar int vertex_indices\n')
    f2.write('end_header\n')
    for i in range(x.shape[0]):
        f2.write('%d %d %d\n' % (x[i], y[i], z[i]))
    for vert in tri.simplices:
        f2.write('3 %d %d %d\n' % (vert[0], vert[1], vert[2]))
    f2.close()
    # 凸面计算体积
    diamond = PyntCloud.from_file(ply_name)
    convex_hull_id = diamond.add_structure("convex_hull")
    convex_hull = diamond.structures[convex_hull_id]
    diamond.mesh = convex_hull.get_mesh()
    # diamond.to_file("bunny_hull.ply", also_save=["mesh"])
    volume = convex_hull.volume
    # 三角剖分结束
    response = {'maxHeight': maxHeight, 'volume': volume, 'minio_url': minio_url}
    print('response ==', response)
    return response


def put_cloud(filepath: str, filename: str):
    object_name = 'cloud_date/' + time.strftime("%Y/%m/%d/") + filename
    # inventory-coal/cloud_date/2022/06/14/a.txt
    minio_conf = settings.MINIO_CONF
    minio_client = minio.Minio(**minio_conf)
    minio_client.fput_object(bucket_name='inventory-coal',
                             object_name=object_name,
                             file_path=filepath,
                             content_type="application/csv")

    minio_path = "http://" + minio_conf['endpoint'] + '/inventory-coal/' + object_name
    print("minio_path == ", minio_path)
    return minio_path


def split_and_calculate_volume(coal_yard, cloud_pdarray):
    res_list = []
    create_time = int(time.strftime('%m%d%H%M%S'))
    # 判断yard_name 文件夹是否存在，不存在创建
    coal_yard_path = settings.DATA_PATH + '/' + coal_yard.coalYardName
    if not os.path.exists(coal_yard_path):
        os.makedirs(coal_yard_path)

    for coal_heap in coal_yard.coalHeapList:
        res = InventoryCoalResult()
        res.coalHeapId = coal_heap.coalHeapId
        res.coalHeapName = coal_heap.coalHeapName
        res.density = coal_heap.density
        res.mesId = coal_heap.mesId
        # print('coal_heap ==', coal_heap)
        minio_name = 'coalHeap' + str(coal_heap.coalHeapId) + '_' + str(create_time) + '.txt'
        minio_path = coal_yard_path + '/' + minio_name
        vom_and_maxhei_and_minio = heap_volume_and_maxheight(coal_heap, cloud_pdarray,
                                                             minio_path=minio_path, minio_name=minio_name)
        # res.cloudInfo = put_cloud(minio_path, minio_name)
        res.cloudInfo = vom_and_maxhei_and_minio['minio_url']
        res.volume = vom_and_maxhei_and_minio['volume']
        res.maxHeight = vom_and_maxhei_and_minio['maxHeight']

        res_list.append(res)

    return res_list
